package com.tanhua.backstage.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.backstage.vo.HtPublishVo;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.backstage.vo.HtMessageVo;
import com.tanhua.backstage.vo.HtPageResult;
import com.tanhua.backstage.vo.HtTotalsVo;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.HtMessageApi.MessageApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.enums.HtTopState;
import com.tanhua.dubbo.server.enums.HtTotals;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.CommentType;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.CommentType;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class HtMessageService {

    @Reference(version = "1.0.0")
    private MessageApi messageApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserInfoMapper userInfoMapper;


    /**
     * 消息拒绝
     *
     * @param publishIds
     * @return
     */
    public Boolean ChangeStateToReject(List<String> publishIds) {
        //如果为空直接返回
        if (CollUtil.isEmpty(publishIds)) {
            return false;
        }
        //如果不为空,则调用dubbo的api进行数据操作
        return this.messageApi.ChangeStateOfPublish(publishIds, HtTotals.PEOPLE_REJECT);

    }


    /**
     * 消息审核通过
     *
     * @param publishIds
     * @return
     */
    public Boolean ChangeStateToPass(List<String> publishIds) {
        //如果为空直接返回
        if (CollUtil.isEmpty(publishIds)) {
            return false;
        }
        //如果不为空,则调用dubbo的api进行数据操作
        return this.messageApi.ChangeStateOfPublish(publishIds, HtTotals.PEOPLE_PASS);

    }

    /**
     * 消息审核通过
     *
     * @param publishIds
     * @return
     */
    public Boolean ChangeStateToRevocation(List<String> publishIds) {
        //如果为空直接返回
        if (CollUtil.isEmpty(publishIds)) {
            return false;
        }
        //如果不为空,则调用dubbo的api进行数据操作
        return this.messageApi.ChangeStateOfPublish(publishIds, HtTotals.PEOPLE_CHECK);

    }


    /**
     * 将选中的状态置顶
     *
     * @param publishId
     * @return
     */
    public Boolean ToTopOfPublish(String publishId) {
        //如果为空直接返回
        if (ObjectUtil.isEmpty(publishId)) {
            return false;
        }
        //如果不为空,则调用dubbo的api进行数据操作
        return this.messageApi.ChangeIsTop(publishId, HtTopState.STICK);
    }

    /**
     * 将选中的状态置顶
     *
     * @param publishId
     * @return
     */
    public Boolean ToUnTopOfPublish(String publishId) {
        //如果为空直接返回
        if (ObjectUtil.isEmpty(publishId)) {
            return false;
        }
        //如果不为空,则调用dubbo的api进行数据操作
        return this.messageApi.ChangeIsTop(publishId, HtTopState.UNSTICK);
    }

    /**
     * 查看单个动态的内容
     *
     * @param publishId
     * @return
     */
    public HtPublishVo queryPublish(String publishId) {
        //如果为空直接返回空
        if (ObjectUtil.isEmpty(publishId)) {
            return null;
        }

        //将获取到的内容封装成需要返回的vo
        HtPublishVo htPublishVo = new HtPublishVo();
        //动态Id
        //htPublishVo.setId(publishId);

        //调用api获取到该publishId的动态详情
        Publish publish = this.messageApi.queryPbublishDetails(publishId);
        htPublishVo.setId(publish.getPid().toString());

        //通过用户Id获取用户信息
        UserInfo userInfo = this.queryUserInfoByUserId(publish.getUserId());

        //封装用户信息
        //作者昵称
        htPublishVo.setNickname(userInfo.getNickName());
        //作者Id
        htPublishVo.setUserId(Convert.toInt(publish.getUserId()));
        //作者头像
        htPublishVo.setUserLogo(userInfo.getLogo());

        //分装vo需要的数据
        //发布时间
        htPublishVo.setCreateDate(publish.getCreated());
        //正文
        htPublishVo.setText(publish.getText());
        //动态里的图片
        htPublishVo.setMedias(publish.getMedias());
        //动态的审核状态
        htPublishVo.setState(publish.getState());
        //动态的置顶状态
        htPublishVo.setTopState(publish.getTopState());

        //调用api获取到该动态的消息的评论详情
        // 获取点赞数
        Long likeCount = quanZiApi.likeAndLoveCount(null, publishId, CommentType.LIKE);
        if (ObjectUtil.isEmpty(likeCount)||likeCount <= 100) {
            htPublishVo.setLoveCount(1000);
        } else {
            htPublishVo.setLoveCount(Convert.toInt(likeCount));
        }
        //获取评论数
        Long commentCount = quanZiApi.likeAndLoveCount(null, publishId, CommentType.COMMENT);
        if (ObjectUtil.isEmpty(commentCount)||commentCount <= 100) {
            htPublishVo.setCommentCount(1000);
        } else {
            htPublishVo.setCommentCount(Convert.toInt(commentCount));
        }
        //获取转发数
        Long tranSmitCount = quanZiApi.likeAndLoveCount(null, publishId, CommentType.TRANSMIT);
        if (ObjectUtil.isEmpty(tranSmitCount)||tranSmitCount <= 100) {
            htPublishVo.setForwardingCount(1000);
        } else {
            htPublishVo.setForwardingCount(Convert.toInt(tranSmitCount));
        }
        //获取举报数
        Long reportCount = quanZiApi.likeAndLoveCount(null, publishId, CommentType.REPORT);
        if (ObjectUtil.isEmpty(reportCount)||reportCount <= 100) {
            htPublishVo.setReportCount(1000);
        } else {
            htPublishVo.setReportCount(Convert.toInt(reportCount));
        }
        return htPublishVo;
    }


    /**
     * 通过用户id获取用户信息
     *
     * @param userId
     * @return
     */
    private UserInfo queryUserInfoByUserId(Long userId) {
        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        UserInfo userInfo = userInfoMapper.selectOne(query);
        return userInfo;
    }

    /**
     * 查询消息列表（全部，或者按照审核状态）
     * 也可以通过消息id单独查询，也可以根据发布时间查询，也可以再时间范围类查询id
     *
     * @param pagesize  分页参数
     * @param page      分页参数
     * @param sortProp  排序字段
     * @param sortOrder 排序方式：ascending 升序 descending 降序
     * @param id        消息id(动态id)
     * @param sd        开始时间
     * @param ed        结束时间
     * @param uid       当前登录者的id（后台管理员id）
     * @param state     审核状态（3，4，5--待审核，已拒绝，已通过）
     * @return 消息列表
     */
    public HtPageResult showMessageList(Integer page, Integer pagesize, String sortProp,
                                        String sortOrder, String id, String sd, String ed, String uid, String state) {
        HtPageResult htPageResult = new HtPageResult();
        htPageResult.setPage(page);
        htPageResult.setPagesize(pagesize);
//        传递参数，远程service从表中获取基础数据，从redis中获取统计数据
//        id是消息关键字查询时给的id
//        uid是通过右下角点击进入时给的id
//        时间处理
        Long startTime = null;
        Long stopTime = null;
        if (!("-1".equals(sd) || "-1".equals(ed))) {
            startTime = Convert.toLong(sd);
            stopTime = Convert.toLong(ed);
        }
        HtTotals htTotals = null;
        if (state != null) {
            //        匹配枚举
            switch (state) {
                case "3": {
                    htTotals = HtTotals.PEOPLE_CHECK;
                    break;
                }
                case "4": {
                    htTotals = HtTotals.PEOPLE_REJECT;
                    break;
                }
                case "5": {
                    htTotals = HtTotals.PEOPLE_PASS;
                    break;
                }
                default:
                    htTotals = HtTotals.ALL;
            }
        } else {
            htTotals = HtTotals.ALL;
        }

//        1.1:获取publish集合;
        PageInfo<Publish> publishPageInfo = messageApi.findPublishList(page, pagesize, sortProp, sortOrder, id,
                startTime, stopTime, uid, htTotals);
        List<Publish> records = publishPageInfo.getRecords();
        Integer total = publishPageInfo.getTotal();
        htPageResult.setCounts(total);
        if (!ObjectUtil.isEmpty(records)) {
//        整合数据
        List<HtMessageVo> htMessageVoList = new ArrayList<>();
        for (Publish record : records) {
            UserInfo userInfo = queryUserInfoByUserId(record.getUserId());
            HtMessageVo htMessageVo = fileHtMessageVo(record, userInfo);
            htMessageVoList.add(htMessageVo);

        }
//        添加HtMessageVo
        htPageResult.setItems(htMessageVoList);
    }else {
            log.error("当前并没有查到任何publish");
            htPageResult.setCounts(0);
            htPageResult.setPages(0);
            List<HtMessageVo> htMessageVoList = new ArrayList<>();
            htPageResult.setItems(htMessageVoList);
            List<HtTotalsVo> htTotalsVoList = new ArrayList<>();
        }

//        添加HtTotalsVo
//        2.1:查询全部的数量
        Long allCount = messageApi.findTotalsCount(HtTotals.ALL,uid,id,startTime,stopTime);
//        2.2：查询待审核数量
        Long checkCount = messageApi.findTotalsCount(HtTotals.PEOPLE_CHECK,uid,id,startTime,stopTime);
//        2.3：查询已通过数量
        Long passCount = messageApi.findTotalsCount(HtTotals.PEOPLE_PASS,uid,id,startTime,stopTime);
//        2.4：查询驳回数量
        Long rejectCount = messageApi.findTotalsCount(HtTotals.PEOPLE_REJECT,uid,id,startTime,stopTime);
//        2.5:查询当前用户动态总数
        Long userCount = messageApi.findUserPublishCount(Convert.toLong(uid));

        List<HtTotalsVo> htTotalsVoList = new ArrayList<>();
        htTotalsVoList.add(new HtTotalsVo("全部", "all", Convert.toInt(allCount)));
        htTotalsVoList.add(new HtTotalsVo("待审核", "3", Convert.toInt(checkCount)));
        htTotalsVoList.add(new HtTotalsVo("已通过", "5", Convert.toInt(passCount)));
        htTotalsVoList.add(new HtTotalsVo("已驳回", "4", Convert.toInt(rejectCount)));
        htPageResult.setTotals(htTotalsVoList);
        if (ObjectUtil.isEmpty(state)) {
            htPageResult.setPages(Convert.toInt(userCount) / pagesize);
        } else {
            switch (state) {
                case "3": {
                    htPageResult.setPages(Convert.toInt(checkCount) / pagesize);
                    break;
                }
                case "4": {
                    htPageResult.setPages(Convert.toInt(rejectCount) / pagesize);
                    break;
                }
                case "5": {
                    htPageResult.setPages(Convert.toInt(passCount) / pagesize);
                    break;
                }
                default:
                    htPageResult.setPages(Convert.toInt(allCount) / pagesize);
            }
        }

        return htPageResult;
    }

    /**
     * 方法：组合HtMessageVo
     *
     * @param record   publish信息
     * @param userInfo 当前用户信息
     * @return HtMessageVo
     */
    private HtMessageVo fileHtMessageVo(Publish record, UserInfo userInfo) {
        HtMessageVo htMessageVo = new HtMessageVo();
        htMessageVo.setId(record.getId().toHexString());
        htMessageVo.setUserId(Convert.toInt(record.getUserId()));
//        htMessageVo.setUserId(1);
        htMessageVo.setNickname(userInfo.getNickName());
        htMessageVo.setUserLogo(userInfo.getLogo());
        htMessageVo.setCreateDate(record.getCreated());
        htMessageVo.setText(record.getText());
        if ("0".equals(record.getState().toString())) {
            htMessageVo.setState("3");
        } else {
            htMessageVo.setState(record.getState().toString());
        }

//            获取点赞数
        Long likeCount = quanZiApi.likeAndLoveCount(null, record.getId().toHexString(), CommentType.LIKE);
        htMessageVo.setLikeCount(Convert.toInt(likeCount));
//            获取评论数
        Long commentCount = quanZiApi.likeAndLoveCount(null, record.getId().toHexString(), CommentType.COMMENT);
        htMessageVo.setCommentCount(Convert.toInt(commentCount));
//            获取转发数
        Long tranSmitCount = quanZiApi.likeAndLoveCount(null, record.getId().toHexString(), CommentType.TRANSMIT);
        htMessageVo.setForwardingCount(Convert.toInt(tranSmitCount));
//            获取举报数
        Long reportCount = quanZiApi.likeAndLoveCount(null, record.getId().toHexString(), CommentType.REPORT);
        htMessageVo.setReportCount(Convert.toInt(reportCount));
//        填充图片信息
        List<String> medias = record.getMedias();
        if (!ObjectUtil.isEmpty(medias)) {
            htMessageVo.setMedias(medias.toArray(new String[medias.size()]));
        }
        return htMessageVo;
    }


}
